const canvas = document.querySelector('#here-we-drawing');
const ctx = canvas.getContext('2d');
ctx.strokeStyle = '#BADA55';
ctx.lineJoin = 'round';
ctx.lineCap = 'round';
ctx.lineWidth = 10;

const parentNodeCanvas = canvas.parentNode;

//State drawing
let isDrawing = false;
let lastX;
let lastY;
let widthTimeoutRef;

const resizeCanvas = () => {
    canvas.width = parentNodeCanvas.offsetWidth;
    canvas.height = parentNodeCanvas.offsetHeight;
    console.log(canvas.width, canvas.height);
};

const drawingHandler = (e) => {
    e.preventDefault();
    if (!isDrawing) return;
    let drawX = e.offsetX, drawY = e.offsetY;
    console.log('when drawing', e);

    if (e.type.includes('touch')) {
        const touch = e.touches[0];
        const touchTarget = touch.target.getBoundingClientRect();

        drawX = touch.clientX - touchTarget.left;
        drawY = touch.clientY - touchTarget.top;
    } 
    

    ctx.beginPath();
    ctx.moveTo(lastX, lastY);
    ctx.lineTo(drawX, drawY);
    ctx.stroke();

    [lastX, lastY] = [drawX, drawY];
};

const startDrawing = (e) => {
    e.preventDefault();
    isDrawing = true;

    if (e.type.includes('touch')) {
        const touch = e.touches[0];
        const touchTarget = touch.target.getBoundingClientRect();

        lastX = touch.clientX - touchTarget.left;
        lastY = touch.clientY - touchTarget.top;
        return;
    }

    lastX = e.offsetX;
    lastY = e.offsetY;
};

const stopDrawing = () => isDrawing = false;

window.addEventListener('resize', resizeCanvas);
canvas.addEventListener('mousemove', drawingHandler);
canvas.addEventListener('mousedown', startDrawing);
canvas.addEventListener('mouseup', stopDrawing);
canvas.addEventListener('mouseout', stopDrawing);
canvas.addEventListener('touchmove', drawingHandler);
canvas.addEventListener('touchstart', startDrawing);
canvas.addEventListener('touchcancel', stopDrawing);
canvas.addEventListener('touchend', stopDrawing);


const setWidthLineHandler = (e) => {
    const {value} = e.target;
    e.target.parentNode.querySelector('.size-width').innerText = value;
    
    if (widthTimeoutRef) {
        clearTimeout(widthTimeoutRef);
        widthTimeoutRef = undefined;
    }
    
    widthTimeoutRef = setTimeout(() => {
        ctx.lineJoin = 'round';
        ctx.lineCap = 'round';
        ctx.lineWidth = value;
    }, 200);
}

const setColorLineHandler = (e) => {
    const {value} = e.target;
    ctx.strokeStyle = value;
}

document.querySelector('.tools__width-line > input')?.addEventListener('mousemove', setWidthLineHandler);
document.querySelector('.tools__width-line > input')?.addEventListener('touchmove', setWidthLineHandler);
document.querySelector('.tools__color-line > input')?.addEventListener('change', setColorLineHandler);

resizeCanvas();